package com.iqiyi.pps.epg.core.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by karkarrotxu on 2015/12/17.
 */
public class StringReplace {
    private String prefix;
    private String suffix;

    private StringReplace(String prefix, String suffix) {
        this.prefix = prefix;
        this.suffix = suffix;
    }

    public String format(String template, Map<String, String> map) {
        List<StringNode> list = new ArrayList<StringNode>();

        StringBuffer sBuff = new StringBuffer();
        int lastIndex = 0;
        int prefixLength = prefix.length();
        int endLength = suffix.length();
        int totalLength = template.length();
        while (true) {
            int start = template.indexOf(prefix, lastIndex);
            if (start == -1) {
                break;
            }
            lastIndex = start + prefixLength;
            int endIndex = template.indexOf(suffix, lastIndex);
            if (endIndex == -1) {
                break;
            }
            StringNode node = new StringNode();
            node.setStartIndex(start);
            node.setEndIndex(endIndex);
            node.setRecordString(template.substring(lastIndex, endIndex));
            list.add(node);
            lastIndex = endIndex + endLength;
            if (totalLength < lastIndex) {
                break;
            }
        }

        int index = 0;
        for (StringNode node : list) {
            if (node.getStartIndex() > index) {
                sBuff.append(template.substring(index, node.getStartIndex()));
                if (map.containsKey(node.getRecordString())) {
                    sBuff.append(map.get(node.getRecordString()));
                } else {
                    sBuff.append(prefix + node.getRecordString() + suffix);
                }
                index = node.getEndIndex() + endLength;
            }
        }
        if (index < totalLength) {
            sBuff.append(template.substring(index, totalLength));
        }
        return sBuff.toString();
    }

    public static StringReplace createUtil(String prefix, String suffix) {
        return new StringReplace(prefix, suffix);
    }
}
